package at.fhj.itm10.ticketmaster.beans;

import java.security.NoSuchAlgorithmException;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.apache.log4j.Logger;

import at.fhj.itm10.ticketmaster.dao.DAOException;
import at.fhj.itm10.ticketmaster.entities.Customer;
import at.fhj.itm10.ticketmaster.helper.MD5HashmakerEmail;
import at.fhj.itm10.ticketmaster.services.ServiceFactory;

/**
 * @author Martin Gritsch
 * @since November 2012
 */
@ManagedBean
@SessionScoped

public class LoginBean {
	
	private Customer customer;
	private ServiceFactory factory;
	private final Logger logger = Logger.getLogger(LoginBean.class);
	
	private String email;
	private String password;
	private String userName;
	private boolean isLoggedIn;

	private String statusL;

	
	public LoginBean(){
		this.init();
	}
	
	@PostConstruct
	public void init() {
    	this.factory = new ServiceFactory();
    	this.statusL = "";
	}

	public String login() {
		try {
			logger.debug("login()");
			this.customer = factory.getCustomerService().findByEMail(this.email);
			logger.debug("customerService " +factory.getCustomerService());
			logger.debug("customer = " + this.customer.toString());
			logger.debug("THIS = " + this);
			if ((this.customer.getPassword().equals(MD5HashmakerEmail.generateMD5Code(this.password))) && (this.customer.isActivated())) {
					this.setLoggedIn(true);
					this.setCustomer(this.customer);
					return "LoggedIn";
			}
			else {
				this.setLoggedIn(false);
				this.statusL = "Falscher Benutzername oder Passwort!";
				return "NotLoggedIn";
			}
		}
		catch (DAOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "NotLoggedIn";
    }
	
    public String getEmail() {
    	return this.email;
    }
    
    public void setEmail(String username) {
    	this.email = username;
    }

    public String getPassword() {
    	return this.password;
    }
    
    public void setPassword(String password) {
    	this.password = password;
    }
    
    public Customer getCustomer() {
    	logger.debug("getCustomer() BEAN)");
    	logger.debug("THIS = " + this);
    	logger.debug("Customer: " + this.customer);
		return this.customer;
	}
    
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public boolean isLoggedIn() {
		return isLoggedIn;
	}

	public void setLoggedIn(boolean isLoggedIn) {
		this.isLoggedIn = isLoggedIn;
	}
	
	public String getStatusL() {
		return this.statusL;
	}
	
	public void setStatusL(String statusL) {
		this.statusL = statusL;
	}
}
